package com.cotte.flow.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cotte.flow.model.DgraphRelations;
import com.cotte.flow.model.DgraphSteps;
import com.cotte.flow.model.Link;
import com.cotte.flow.model.Relation;
import com.cotte.flow.model.Step;
import com.cotte.flow.util.Client;
import com.cotte.flow.util.Transform;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;

import io.dgraph.DgraphClient;
import io.dgraph.DgraphProto.Mutation;
import io.dgraph.DgraphProto.Operation;
import io.dgraph.DgraphProto.Response;
import io.dgraph.Transaction;
import net.sf.json.JSONObject;

@Service
public class StepDgraphService {
	private static final Logger logger = LoggerFactory.getLogger(StepDgraphService.class);
	private static DgraphClient dgraphClient = Client.createDgraphClient(false);
	private static Gson gson = new Gson();
	
	@Value("${dgraph.steps.name.prefix}")
	private String STEP_NAME;
	@Value("${dgraph.relations.name.prefix}")
	private String RELATION_NAME;
	
	// 裁剪组
	private static String[] s106to2 = new String[] { "2", "109" };
	private static String[] s106to239 = new String[] { "239", "3" };
	private static String[] s106to107 = new String[] { "107" };

	private static String[] s8to378 = new String[] { "378", "379", "653" };
	private static String[] s8to12 = new String[] { "12", "430" };
	// 西服二组
	private static String[] s62to63 = new String[] {"63", "64",
			"65", "66", "60", "67", "74", "70", "75", "451", "76", "77", "82",
			"538", "83", "79", "80", "81", "205", "110", "111", "84", "112",
			"113", "114", "115" };
	private static String[] s62to68 = new String[] { "68", "542", "69", "241",
			"71" };
	private static String[] s62to72 = new String[] { "72", "73" };
	// 西服三组
	private static String[] s213to481 = new String[] { "481", "673", "490",
			"671", "672", "674" };
	private static String[] s213to663 = new String[] { "663", "662", "664",
			"665" };
	private static String[] s213to135 = new String[] { "135" };
	// 西服一组
	private static String[] s51to41 = new String[] { "41", "45", "43", "455",
			"46", "47", "48", "59", "49", "516", "50", "456", "58", "53",
			"513", "216", "44", "514", "54", "515", "55", "517", "56", "52",
			"483", "57" };
	private static String[] s51to42 = new String[] { "42", "40" };

	private static String[] s26to492 = new String[] { "492", "220", "20",
			"203", "472", "21", "25", "485", "22", "105", "24", "486", "157",
			"29", "32", "30", "31", "33", "34", "35", "93", "545", "487",
			"512", "38" };
	// 西服四组
	private static String[] s430to165 = new String[] { "165", "167", "168",
			"164", "169", "162", "163" };
	// 整烫组
	private static String[] s197to311 = new String[] { "311" };
	private static String[] s197to312 = new String[] { "312" };
	
	public void getName() {
		System.out.println("STEP_NAEM:"+STEP_NAME);
	}
	
	/**
	 * 
	 * <p>Title: setStep</p>  
	 * <p>Description: </p>  
	 * @param version
	 * @throws Exception
	 */
	public String setStep(String department,String cate,String version) throws Exception{
		Transaction txn = dgraphClient.newTransaction();
		//Random random = new Random();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
		// 清空数据
		//dgraphClient.alter(Operation.newBuilder().setDropAll(true).build());
		String schema = "D_steps_name: String@index(hash, trigram) .\n"
				+ " key: String @index(hash) .\n "
				+ " text: String @index(hash) .\n "
				+ " stepname: String @index(hash) .\n "
				+ " category: String @index(hash) .\n "
				+ " group: String@index(hash) .\n"
				+"  isWhere: String .\n"
				+" occupy: String . \n"
				+" occupy_next: String .\n"
				+" occupy_pre: String .\n"
				+" zOrder: String .\n"
				+" odid: String .\n"
				+" visible: String .\n";
    	Operation op = Operation.newBuilder().setSchema(schema).build();
    	dgraphClient.alter(op);
		// 组建DgraphSteps
		DgraphSteps dgraphSteps = new DgraphSteps();
		//根据文件名称组织态势图名称
		String stepFileName = department+"_"+cate+"_STEPS";
		String time = df.format(new Date());
		String name = version+"_"+department+"_"+cate+"_"+time;
		dgraphSteps.setD_steps_name(STEP_NAME+name);
		try {
			// 获取工序节点信息，读取文件保存step
			List<Step> steps = new ArrayList<Step>();
			String path = "/file/"+stepFileName+".txt";
			InputStream is = this.getClass().getResourceAsStream(path);
			//final String nodePath = this.getClass().getResource("/").getPath() + "file/"+stepFileName+".txt";
			//InputStream is = new FileInputStream(nodePath);
			String line = null;
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			line = reader.readLine();
			while (line != null) {
				String[] arr = line.split("\t"); 
				if (arr.length == 2) {
					Step step = new Step();
					step.setKey(arr[0]);
					step.setStepname(arr[1]);
					if("start".equals(arr[0])) {
						step.setisGroup(false);
						step.setCategory("Start");
					}else if("end".equals(arr[0])) {
						step.setisGroup(false);
						step.setCategory("End");
					}else {
						step.setisGroup(true);
						step.setCategory(arr[1]);
					}
					steps.add(step);
				}else if(arr.length == 5 || arr.length == 4) {
					Step step = new Step();
					step.setKey(arr[0]);
					step.setStepname(arr[1]);
					step.setText(arr[0] + "-" + arr[1]);
					step.setGroup(arr[2]);
					step.setCategory(arr[3]);
					step.setisGroup(false);
					/*int random_pre = random.nextInt(MAX_VALUE);
					step.setOccupy_pre(String.valueOf(random_pre));
					if(random_pre > OVER_COUNT) {
						step.setOccupy_pre_valid(true);
					}else {
						step.setOccupy_pre_valid(false);
					}
					int random_next = random.nextInt(MAX_VALUE);
					step.setOccupy_next(String.valueOf(random_next));
					if(random_next > OVER_COUNT) {
						step.setOccupy_next_valid(true);
					}else {
						step.setOccupy_next_valid(false);
					}*/
					if (arr.length == 5) {
						step.setIsWhere(arr[4]);
					}
					step.setzOrder("0");
					steps.add(step);
				}
				line = reader.readLine();
			}
			logger.info("共生成节点:" + steps.size() + "个");
			reader.close();
			is.close();
			//DgraphSteps 添加step信息
			dgraphSteps.setSteps(steps);
			String json = gson.toJson(dgraphSteps);
			//数据保存
			ByteString muValue = ByteString.copyFromUtf8(json.toString());
	    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
	    	txn.mutate(mu);
		}finally {
			txn.discard();
		}
		return name;
	}
	/**
	 * 
	 * <p>Title: setRelation</p>  
	 * <p>Description: </p>  
	 * @param version
	 * @throws Exception
	 */
	public void setRelation(String department,String cate,String name) throws Exception{
	//	Random random = new Random();
		Transaction txn = dgraphClient.newTransaction();
		// 清空数据
		//dgraphClient.alter(Operation.newBuilder().setDropAll(true).build());
		String schema = " D_relations_name: String @index(hash, trigram) .\n"
				+" from: String @index(hash) .\n"
				+" to: String @index(hash) .\n";
    	Operation op = Operation.newBuilder().setSchema(schema).build();
    	dgraphClient.alter(op);
		// 组建DgraphRelations
		DgraphRelations dgraphRelations = new DgraphRelations();
		dgraphRelations.setD_relations_name(RELATION_NAME+name);
		String relationFileName = department+"_"+cate+"_RELATIONS";
		try {
			// 获取工序关系信息
			List<Relation> relations = new ArrayList<Relation>();
			String path = "/file/"+relationFileName+".txt";
			InputStream is = this.getClass().getResourceAsStream(path);
			//final String nodePath = this.getClass().getResource("/").getPath() + "file/"+relationFileName+".txt";
			//InputStream is = new FileInputStream(nodePath);
			String line = null;
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			line = reader.readLine();
			while (line != null) {
				String[] arr = line.split("\t");
				Relation relation = new Relation();
				relation.setFrom(arr[0]);
				relation.setTo(arr[1]);
				relation.setWarn(arr[2]);
				//int random_occ = random.nextInt(MAX_VALUE);
				relation.setOccupy(String.valueOf(0));
				/*if(random_occ > OVER_COUNT) {
					relation.setOccupy_valid(true);
				}else {
					relation.setOccupy_valid(false);
				}*/
				relations.add(relation);
				line = reader.readLine();
			}
			logger.info("共生成关系:" + relations.size() + "个");
			reader.close();
			is.close();
			//DgraphRelations 添加relation信息
			dgraphRelations.setRelations(relations);
			String json = gson.toJson(dgraphRelations);
			//数据保存
			ByteString muValue = ByteString.copyFromUtf8(json.toString());
	    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
	    	txn.mutate(mu);
		}finally {
			txn.discard();
		}
	}
	/**
	 * 
	 * <p>Title: addRelation</p>  
	 * <p>Description: </p>  
	 * @param version
	 */
	public void addRelation(String version) {
		Transaction txn = dgraphClient.newTransaction();
    	DgraphSteps steps = getDgraphSteps(version);
    	List<Step> new_steps = new ArrayList<Step>();
    	for(Step st:steps.getSteps()) {
    		if(!"group".equals(st.getCategory()) && !"End".equals(st.getCategory()) &&  !"手工组".equals(st.getGroup())) {
        		String stepcode = st.getKey();
        		System.out.println("stepcode:"+stepcode);
        		String queryNextStep="{\n"+
        				"var(func:eq(D_relations_name,%s)){\r\n" + 
        				"    relations @filter(eq(from,%s)){\r\n" + 
        				"      nextStep as to\r\n" + 
        				"    }\r\n" + 
        				"  }\r\n"+
        				"getStep(func:eq(D_steps_name,%s)){\r\n" + 
        				"    steps @filter(eq(key,val(nextStep))){\r\n" + 
        				"      uid \n key\r\n" + 
        				"      stepname\r\n text \r\n" + 
        				"    }\r\n" + 
        				"  }\n" +
        				"}";
        		String query = String.format(queryNextStep, RELATION_NAME+version,stepcode,STEP_NAME+version);
        		Response response = dgraphClient.newReadOnlyTransaction().query(query);
        		String next_json = Transform.jsonTransform(response,"getStep");
            	DgraphSteps next_steps = gson.fromJson(next_json, DgraphSteps.class);
            	st.setChild(next_steps.getSteps());
            	new_steps.add(st);
    		}
    	}
    	steps.setSteps(new_steps);
    	String js = gson.toJson(steps);
 		//数据保存
 		ByteString muValue = ByteString.copyFromUtf8(js.toString());
     	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
     	txn.mutate(mu);
	}
	
	/**
	 * 
	 * <p>Title: getDgraphSteps</p>  
	 * <p>Description: </p>  
	 * @param version
	 * @return
	 */
	public  DgraphSteps getDgraphSteps(String stepName) {
		//根据名字找到图数据库中对应的图
		String queryDgraph="{\n" + 
				"  queryDgraph(func:eq(D_steps_name,%s)){\n" + 
				"    uid\n" + 
				"    parentStep\n"+
				"    steps{\n" + 
				"      uid\n" + 
				"      key\n" + 
				"      text\n" + 
				"      category\n" + 
				"      isGroup\n" + 
				"      group\n" + 
				"      isNouse\n"+
				"      isWhere\n" + 
				"      zOrder\n" + 
				"      pos\n"+
				"      odid\n"+
				"      visible\n"+
				"    }\n" + 
				"  }\n" + 
				"}";
		String format = String.format(queryDgraph, stepName);
		Response response = dgraphClient.newReadOnlyTransaction().query(format);
		String json = Transform.jsonTransform(response,"queryDgraph");
		DgraphSteps dgraphSteps = gson.fromJson(json, DgraphSteps.class);
		return dgraphSteps;
	}
	
	/**
	 * 
	 * <p>Title: getDgraphRelation</p>  
	 * <p>Description: </p>  
	 * @param version
	 * @return
	 */
	public  DgraphRelations getDgraphRelation(String relationName) {
		//根据名字找到图数据库中对应的图
		String queryDgraph="{\n" + 
				"  queryDgraph(func:eq(D_relations_name,%s)){\n" + 
				"    uid\n" + 
				"    parentRelation\n"+
				"    relations{\n" + 
				"      uid\n" + 
				"      from\n" + 
				"      to\n" + 
				"      occupy\n" + 
				"      occupy_valid\n" +
				"      points\n"+
				"      fromPort\n"+
				"      toPort\n"+
				"      warn\n"+
				"      transit\n"+
				"    }\n" + 
				"	  links{\n" + 
				"      uid\n" + 
				"      from\n" + 
				"      to\n" + 
				"      occupy\n" + 
				"      occupy_valid\n" +
				"      points\n"+
				"      fromPort\n"+
				"      toPort\n"+
				"    }\n" + 
				"  }\n" + 
				"}";
		String format = String.format(queryDgraph, relationName);
		Response response = dgraphClient.newReadOnlyTransaction().query(format);
		String json = Transform.jsonTransform(response,"queryDgraph");
		DgraphRelations dgraphRelations = gson.fromJson(json, DgraphRelations.class);
		return dgraphRelations;
	}
	/**
	 * 校验占压是否达到预警值
	 * <p>Title: checkOccupy</p>  
	 * <p>Description: </p>  
	 * @param relations
	 * @return
	 */
	public List<Relation> checkOccupy(List<Relation> relations) {
		boolean occupy_valid = false;
		if(null != relations && relations.size() > 0) {
			for(Relation rel:relations) {
				//开始节点不显示占压
				if("start".equals(rel.getFrom()) || "end".equals(rel.getTo())) {
					String occupy = "";
					rel.setOccupy(occupy);
					rel.setOccupy_valid(occupy_valid);
				}else{
					String occupy = rel.getOccupy();
					String warn = rel.getWarn();
					if(Integer.valueOf(occupy) > 100) {
						occupy_valid = true;
						rel.setOccupy_valid(occupy_valid);
					}
				}
			}
		}
		return relations;
		
	}
	
	
	/**
	 * 更新relations的信息
	 * <p>Title: updateRelations</p>  
	 * <p>Description: </p>  
	 * @param name
	 */
	public void updateRelations(String name) {
		DgraphRelations dgraph_relations = getDgraphRelation(name);
		List<Relation> relations = dgraph_relations.getRelations();
		for(Relation rel:relations) {
			rel.setOccupy(String.valueOf(0));
		}
	}
	/**
	 * 
	 * <p>Title: saveStepsPorts</p>  
	 * <p>Description: </p>  
	 * @param steps
	 * @param version
	 */
	public void saveStepsPorts(Object steps,String name) {
		Transaction txn = dgraphClient.newTransaction();
		//将Object 转成 List<Step>
		List<Step> d_steps = (List<Step>) steps;
		String stepName = STEP_NAME+name;
		DgraphSteps dgraphSteps = getDgraphSteps(stepName);
		dgraphSteps.setSteps(d_steps);
		//数据保存
		String steps_json = gson.toJson(dgraphSteps);
		ByteString muValue = ByteString.copyFromUtf8(steps_json.toString());
    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
    	txn.mutate(mu);
	}
	
	/**
	 * v1版本的更新节点位置
	 * <p>Title: saveStepsPortsOld</p>  
	 * <p>Description: </p>  
	 * @param steps
	 * @param name
	 */
	public void saveStepsPortsOld(Object steps,String name) {
		Transaction txn = dgraphClient.newTransaction();
		//将Object 转成 List<Step>
		List<Step> d_steps = (List<Step>) steps;
		String stepName = STEP_NAME+name;
		DgraphSteps dgraphSteps = getDgraphSteps(stepName);
		List<Step> stepsOld = dgraphSteps.getSteps();
		List<Step> newSteps = new ArrayList<>();
		for(Step st:stepsOld) {
			String key = st.getKey();
			//更新传过来的数据
			for(Object newSt:d_steps) {
				JSONObject obj = JSONObject.fromObject(newSt);
				Step step = (Step) JSONObject.toBean(obj, Step.class);
				if(key.equals(step.getKey())) {
					st.setPos(step.getPos());
				}
			}
			newSteps.add(st);
		}
		dgraphSteps.setSteps(newSteps);
		//数据保存
		String steps_json = gson.toJson(dgraphSteps);
		ByteString muValue = ByteString.copyFromUtf8(steps_json.toString());
    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
    	txn.mutate(mu);
	}
	
	/**
	 * 
	 * <p>Title: saveLinkPoints</p>  
	 * <p>Description: </p>  
	 * @param relations
	 * @param version
	 */
	public void saveLinkPoints(Object relations,String name) {
		Transaction txn = dgraphClient.newTransaction();
		//将Object 转成 List<Relation>
		List<Relation> d_relations = (List<Relation>) relations;
		String relationName = RELATION_NAME+name;
		DgraphRelations dgraphRelations = getDgraphRelation(relationName);
		List<Relation> relationsOld = dgraphRelations.getRelations();
		List<Relation> newRelations = new ArrayList<>();
		for(Relation rel:relationsOld) {
			String from = rel.getFrom();
			String to = rel.getTo();
			//更新传过来的数据
			for(Object newRel:d_relations) {
				JSONObject obj = JSONObject.fromObject(newRel);
				Relation relation = (Relation) JSONObject.toBean(obj, Relation.class);
				if(from.equals(relation.getFrom()) && to.equals(relation.getTo())) {
					rel.setPoints(relation.getPoints());
					rel.setFromPort(relation.getFromPort());
					rel.setToPort(relation.getToPort());
				}
			}
			newRelations.add(rel);
		}
/*		String root_uid = dgraphRelations.getUid();
		List<Relation> newRelations = new ArrayList<>();
		//先删掉原来的线
		for(Object rel:d_relations) {
			JSONObject obj = JSONObject.fromObject(rel);
			Relation relation = (Relation) JSONObject.toBean(obj, Relation.class);
			String from = relation.getFrom();
			String to = relation.getTo();
			String uid = relation.getUid();
			String occupy = relation.getOccupy();
			
			boolean occupy_valid = relation.isOccupy_valid();
			if(null == uid) {
				System.out.println("from:"+from+"to:"+to);
				//根据from和to删除原来的线
				String getUid = "{\n" + 
						"  getUid(func:eq(D_relations_name,%s)){\n" + 
						"    relations @filter(eq(from,%s) and eq(to,%s)){\n" + 
						"      uid\n" + 
						"      from\n" + 
						"      to\n" + 
						"      occupy\n"+
						"      occupy_valid\n"+
						"    }\n" + 
						"  }\n" + 
						"}";
				String query = String.format(getUid, relationName,from,to);
				Response res = dgraphClient.newReadOnlyTransaction().query(query);
				String json_uid = Transform.jsonTransform(res,"getUid");
				DgraphRelations dgraphRel = gson.fromJson(json_uid, DgraphRelations.class);
				//if(dgraphRel.getRelations().size() > 0) {
					for(Relation relat :dgraphRel.getRelations()) {
						Transaction txn_del = dgraphClient.newTransaction();
						occupy = relat.getOccupy();
						occupy_valid = relat.isOccupy_valid();
						String uid_rel = relat.getUid();
						Mutation mutation =Mutation.newBuilder().setCommitNow(true)
								.setDelNquads(
										ByteString.copyFromUtf8(
												String.format("<%s> <relations> <%s> .",root_uid,uid_rel)
												)
										).build();
						txn_del.mutate(mutation);
					}
				//}
			}
			relation.setOccupy(occupy);
			relation.setOccupy_valid(occupy_valid);
			newRelations.add(relation);
		}*/
		
		dgraphRelations.setRelations(newRelations);
		//数据保存
		String relations_json = gson.toJson(dgraphRelations);
		ByteString muValue = ByteString.copyFromUtf8(relations_json.toString());
    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
    	txn.mutate(mu);
	}
	
	/**
	 * 
	 * <p>Title: saveLink</p>  
	 * <p>Description: </p>  
	 * @param links
	 * @param version
	 */
	public void saveLink(Object links,String name) {
		Transaction txn = dgraphClient.newTransaction();
		//将Object 转成 List<Step>
		List<Link> d_link = (List<Link>) links;
		//找到相应的关系图
		String relationName = RELATION_NAME+name;
		DgraphRelations dgraphRelations = getDgraphRelation(relationName);
		//如果有数据需要先删除原来的数据，重新保存新数据
		String root_uid = dgraphRelations.getUid();
		Transaction txn_del = dgraphClient.newTransaction();
		Mutation mutation =Mutation.newBuilder().setCommitNow(true)
				.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> <links> * .", root_uid))).build();
		txn_del.mutate(mutation);
		//数据保存
		dgraphRelations.setLinks(d_link);
		String Link_json = gson.toJson(dgraphRelations);
		ByteString muValue = ByteString.copyFromUtf8(Link_json.toString());
    	Mutation mu = Mutation.newBuilder().setCommitNow(true).setSetJson(muValue).build();
    	txn.mutate(mu);
	}
	
	public Map<String,Map<String,List<String>>> fzMap(){
		Map<String, Map<String, List<String>>> fzMap = new LinkedHashMap<String, Map<String, List<String>>>();
		// 裁剪组
		List<String> list106to107 = Arrays.asList(s106to107);
		List<String> list106to2 = Arrays.asList(s106to2);
		List<String> list106to239 = Arrays.asList(s106to239);
		List<String> list8to378 = Arrays.asList(s8to378);
		List<String> list8to12 = Arrays.asList(s8to12);
		// 西服二组
		List<String> list62to68 = Arrays.asList(s62to68);
		List<String> list62to72 = Arrays.asList(s62to72);
		List<String> list62to63 = Arrays.asList(s62to63);
		// 西服三组
		List<String> list213to663 = Arrays.asList(s213to663);
		List<String> list213to481 = Arrays.asList(s213to481);
		List<String> list213to135 = Arrays.asList(s213to135);
		// 西服一组
		List<String> list51to41 = Arrays.asList(s51to41);
		List<String> list51to42 = Arrays.asList(s51to42);
		List<String> list26to492 = Arrays.asList(s26to492);

		// 西服四组
		List<String> list430to165 = Arrays.asList(s430to165);

		// 整烫组
		List<String> list197to311 = Arrays.asList(s197to311);
		List<String> list197to312 = Arrays.asList(s197to312);

		Map<String, List<String>> map106 = new LinkedHashMap<String, List<String>>();
		map106.put("106_2", list106to2);
		map106.put("106_239", list106to239);
		map106.put("106_107", list106to107);

		Map<String, List<String>> map8 = new LinkedHashMap<String, List<String>>();
		map8.put("8_378", list8to378);
		map8.put("8_12", list8to12);

		Map<String, List<String>> map61er = new LinkedHashMap<String, List<String>>();
		map61er.put("62_236", list62to63);
		map61er.put("62_72", list62to72);
		map61er.put("62_68", list62to68);

		Map<String, List<String>> map213san = new LinkedHashMap<String, List<String>>();
		map213san.put("213_481", list213to481);
		map213san.put("213_663", list213to663);
		map213san.put("213_135", list213to135);

		Map<String, List<String>> map51 = new LinkedHashMap<String, List<String>>();
		map51.put("51_41", list51to41);
		map51.put("51_42", list51to42);

		Map<String, List<String>> map26 = new LinkedHashMap<String, List<String>>();
		map26.put("26_492", list26to492);

		Map<String, List<String>> map430 = new LinkedHashMap<String, List<String>>();
		map430.put("430_165", list430to165);

		Map<String, List<String>> map197 = new LinkedHashMap<String, List<String>>();
		map197.put("197_311", list197to311);
		map197.put("197_312", list197to312);

		fzMap.put("106", map106);
		fzMap.put("8", map8);
		fzMap.put("62", map61er);
		fzMap.put("_213", map213san);
		fzMap.put("51", map51);
		fzMap.put("26", map26);
		fzMap.put("430", map430);
		fzMap.put("197", map197);
		return fzMap;
	}
	
	/**
	 * 
	 * <p>Title: getFzRel</p>  
	 * <p>Description: </p>  
	 * @param version
	 * @return
	 */
	public Map<String,Map<String,List<String>>> getFzRel(String version) {
		Map<String,Map<String,List<String>>> fzMap = new LinkedHashMap<>();
		//获取next_step 数大于1的所有节点
		DgraphSteps steps = getDgraphSteps(version);
		List<Step> allSteps = steps.getSteps();
		for(Step st:allSteps) {
			List<Step> childs = st.getChild();
			if(childs != null) {
				int childCount = childs.size();
				if(childCount > 1) {
					//106
					String key = st.getKey();
					String group = st.getGroup();
					if(!"start".equals(key)) {
						Map<String,List<String>> tempMap = new LinkedHashMap<>();
						for(Step ch:childs) {
							//2
							String child_key = ch.getKey();
							//String child_group = ch.getGroup();
							List<String> tempList = new ArrayList<>();
							//tempList.add(child_key);
							//拿着child_key 和 child_group 去child_key的child 节点。child_group 不满足则跳出
							tempList = getTempList(tempList,child_key,group,version);
							if(tempList != null && tempList.size() > 0) {
								tempMap.put(key+"_"+child_key, tempList);
							}
						}
						if(!tempMap.isEmpty()) {
							fzMap.put(key, tempMap);
						}
					}
				}
			}
		}
		
		return fzMap;
	}
	
	/**
	 * 分支
	 * <p>Title: getTempList</p>  
	 * <p>Description: </p>  
	 * @param key
	 * @param group
	 * @param version
	 * @return
	 */
	private List<String> getTempList(List<String> tempList,String key,String group,String version) {
		String queryChild = "{\n" + 
				"  \n" + 
				"	queryChild(func:eq(D_steps_name,%s)){\n" + 
				"    uid\n" + 
				"    steps @filter(eq(key,%s) and eq(group,\"%s\")){\n" + 
				"      uid\n" + 
				"      key\n" + 
				"      child @filter(eq(group,\"%s\")){\n" + 
				"        key\n" + 
				"        stepcode\n" + 
				"        text\n" + 
				"        group\n" + 
				"      }\n" + 
				"    }\n" + 
				"  }\n" + 
				"}";
		String format = String.format(queryChild, STEP_NAME+version,key.toString(),group.toString(),group.toString());
		Response response = dgraphClient.newReadOnlyTransaction().query(format);
		String json = Transform.jsonTransform(response,"queryChild");
		DgraphSteps dgraphSteps = gson.fromJson(json, DgraphSteps.class);
		List<Step> next_steps = dgraphSteps.getSteps();
		if(next_steps == null || "end".equals(next_steps.get(0).getKey())) {
			return tempList;
		}else {
			tempList.add(key);
			if(null != next_steps.get(0).getChild()) {
				String key_child = next_steps.get(0).getChild().get(0).getKey();
				tempList = getTempList(tempList,key_child,group,version);
			}
		}
		return tempList;
	}
	
	/**
	 * 
	 * <p>Title: getAllVersion</p>  
	 * <p>Description: </p>  
	 * @return
	 */
	public List<String> getAllVersion(String version){
		List<String> allVersion = new ArrayList<>();
		String queryAll = "{\n" + 
				"  all(func:regexp(D_steps_name, /^Steps_%s.*$/)){\n" + 
				"    uid\n" + 
				"    D_steps_name\n" + 
				"  }\n" + 
				"}";
		String format = String.format(queryAll,version);
		Response response = dgraphClient.newReadOnlyTransaction().query(format);
		String json = response.getJson().toStringUtf8();
		Map<String,JSONArray> maps = (Map<String,JSONArray>)JSON.parse(json); 
		JSONArray array = maps.get("all");
		if(null != array && array.size() > 0) {
			for(int i=0;i<array.size();i++) {
				// 遍历 jsonarray 数组，把每一个对象转成 json 对象
				com.alibaba.fastjson.JSONObject job = array.getJSONObject(i); 
				String name = (String) job.get("D_steps_name");
				allVersion.add(name);
			}
		}
		return allVersion;
	}
	
	/**
	 * 
	 * <p>Title: deleteDgraph</p>  
	 * <p>Description: </p>  
	 * @param version
	 */
	public void deleteDgraph(String name) {
		String stepName = "OrderSteps_"+name;
		String relationName = "OrderRelations_" + name;
		
		DgraphSteps dgraphSteps = getDgraphSteps(stepName);
		
		DgraphRelations dgraphRelations = getDgraphRelation(relationName);
		Transaction txn_del = dgraphClient.newTransaction();
		if(null != dgraphSteps) {
			String stepRootUid = dgraphSteps.getUid();
			//删除steps
			Mutation mutation =Mutation.newBuilder()
					.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> <steps> * .", stepRootUid))).build();
			txn_del.mutate(mutation);
			//删除root
			Mutation step_mutation =Mutation.newBuilder()
					.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> * * .", stepRootUid))).build();
			txn_del.mutate(step_mutation);
		}
		
		if(null != dgraphRelations) {
			String relationRootUid = dgraphRelations.getUid();
			//删除relations
			Mutation mutation =Mutation.newBuilder()
					.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> <relations> * .", relationRootUid))).build();
			txn_del.mutate(mutation);
			//删除links
			Mutation mutation_link =Mutation.newBuilder()
					.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> <links> * .", relationRootUid))).build();
			txn_del.mutate(mutation_link);
			//删除root
			Mutation rel_mutation =Mutation.newBuilder()
					.setDelNquads(ByteString.copyFromUtf8(String.format("<%s> * * .", relationRootUid))).build();
			txn_del.mutate(rel_mutation);
		}
		txn_del.commit();
	}
}
